package com.smart.status.payment.alipay;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.AlipayConfig;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.domain.*;
import com.alipay.api.request.*;
import com.alipay.api.response.*;
import com.smart.status.payment.alipay.constants.AlipayConstants;
import com.smart.status.payment.alipay.vo.AlipayPaymentVo;
import com.smart.status.payment.handler.PaymentHandler;
import com.smartStatus.core.util.R;
import lombok.AllArgsConstructor;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.dom4j.DocumentHelper;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.springframework.stereotype.Component;

import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @Author: liuby5
 * @CreateTime: 2022-09-07  15:14
 * @Description: 阿里支付
 * @Version: 1.0
 */
@Component(value = "A_LI_PAY")
@AllArgsConstructor
@Slf4j
public class AlipayPaymentHandler implements PaymentHandler {

    /**
     * 初始化支付参数
     *
     * @return
     */
    public AlipayClient initClient() {
        log.info("支付宝支付开始初始化支付信息:{}", AlipayConstants.APPID);
        AlipayConfig alipayConfig = new AlipayConfig();
        alipayConfig.setServerUrl(AlipayConstants.URL);
        alipayConfig.setAppId(AlipayConstants.APPID);
        alipayConfig.setPrivateKey(AlipayConstants.PRIVATE_KEY);
        alipayConfig.setFormat(AlipayConstants.FORMAT);
        alipayConfig.setAlipayPublicKey(AlipayConstants.ALIPAY_PUBLIC_KEY);
        alipayConfig.setCharset(AlipayConstants.CHARSET);
        alipayConfig.setSignType(AlipayConstants.SIGN_TYPE);
        AlipayClient alipayClient = null;
        try {
            alipayClient = new DefaultAlipayClient(alipayConfig);
            log.info("支付宝支付初始化完成，创建支付对象成功");
        } catch (AlipayApiException e) {
            log.info("支付宝支付初始化失败:{}", e.getErrMsg());
            e.printStackTrace();
            return null;
        }
        return alipayClient;
    }

    @Override
    public R verificationCodePay(AlipayPaymentVo paymentVo) {
        try {
            AlipayClient alipayClient = this.initClient();
            AlipayTradePagePayRequest request = new AlipayTradePagePayRequest();
            // 初始化请求对象内容
            AlipayTradePagePayModel model = new AlipayTradePagePayModel();
            // 订单号
            log.info("支付宝支付生成支付页面开始拼接参数");
            String outTradeNo = UUID.randomUUID().toString().replace("-", "");
            model.setOutTradeNo(outTradeNo);
            // 订单金额
            model.setTotalAmount("88.88");
            // 订单描述
            model.setSubject("Iphone6 16G");
            // 电脑支付场景码值
            model.setProductCode("FAST_INSTANT_TRADE_PAY");
            // PC扫码支付的方式  4: 可设置宽度的二维码
            model.setQrPayMode("4");
            // 如果设置了支付方位为4，则设置二维码大小
            model.setQrcodeWidth(new Long("100"));
            // 商品详细信息
            List<GoodsDetail> goodsDetailList = new ArrayList<>();
//            model.setGoodsDetail(goodsDetailList);
            // 订单超时时间 2016-12-31 10:05:01  设置1分钟超时
            model.setTimeExpire(this.getTimeOutDate(3));
            // 优惠参数。为 JSON 格式。注：仅与支付宝协商后可用
//            model.setPromoParams("");
            // 用户中途停止支付时，跳转地址
            model.setRequestFromUrl("http://www.baidu.com");
            request.setBizModel(model);
            log.info("支付宝支付请求开始参数为:{}", request.getBizModel());
            AlipayTradePagePayResponse response = alipayClient.pageExecute(request);
            log.info("支付宝支付请求结束参数为:{}", response.toString());
            if (response.isSuccess()) {
                log.info("支付宝支付接口调用成功，获取到支付页面数据为:{}", response.getBody());
            } else {
                log.info("支付宝支付接口调用失败，失败原因:{}", response.getMsg());
            }
            return R.ok(response.getBody());
        } catch (AlipayApiException e) {
            e.printStackTrace();
            return R.failed("支付宝支付接口调用失败，系统异常");
        }
    }


    @Override
    public R refundPay(AlipayPaymentVo paymentVo) {
        AlipayClient alipayClient = this.initClient();
        AlipayTradeRefundRequest request = new AlipayTradeRefundRequest();
        AlipayTradeRefundModel model = new AlipayTradeRefundModel();
        // 商户订单号。 支付时的订单号
        String outTradeNo = UUID.randomUUID().toString().replace("-", "");
        model.setOutTradeNo(outTradeNo);
        log.info("支付宝支付退款流程开始,退款订单号为:{}", outTradeNo);
        // 支付宝交易号 通订单号
        model.setTradeNo("");
        // 退款金额
        model.setRefundAmount("200.12");
        request.setBizModel(model);
        try {
            log.info("支付宝支付请求开始参数为:{}", JSON.toJSONString(request.getBizModel()));
            AlipayTradeRefundResponse response = alipayClient.execute(request);
            log.info("支付宝支付请求结束，请求结果为:{}", JSON.toJSONString(response));
            if (response.isSuccess()) {
                log.info("支付宝支付请求成功，请求结果为:{}", response.getBody());
            } else {
                log.info("支付宝支付请求失败，失败原因为:{}", response.getSubMsg());
            }
            return R.ok(response.getBody());
        } catch (AlipayApiException e) {
            e.printStackTrace();
            return R.failed("支付系统异常");
        }

    }


    @Override
    public R refundQuery(AlipayPaymentVo paymentVo) {
        AlipayClient alipayClient = this.initClient();
        AlipayTradeFastpayRefundQueryRequest request = new AlipayTradeFastpayRefundQueryRequest();
        AlipayTradeFastpayRefundQueryModel model = new AlipayTradeFastpayRefundQueryModel();
        // 订单号
        model.setOutTradeNo("HZ01RF001");
        model.setOutRequestNo("HZ01RF001");
        request.setBizModel(model);
        try {
            log.info("支付宝支付请求开始参数为:{}", JSON.toJSONString(request.getBizModel()));
            AlipayTradeFastpayRefundQueryResponse response = alipayClient.execute(request);
            log.info("支付宝支付请求结束，请求结果为:{}", JSON.toJSONString(response));
            if (response.isSuccess()) {
                log.info("支付宝支付请求成功，请求结果为:{}", response.getBody());
            } else {
                log.info("支付宝支付请求失败，失败原因为:{}", response.getSubMsg());
            }
            return R.ok(response.getBody());
        } catch (AlipayApiException e) {
            e.printStackTrace();
            return R.failed("系统异常");

        }
    }

    @Override
    public R appSignPay(AlipayPaymentVo paymentVo) {
        AlipayClient alipayClient = this.initClient();
        AlipayTradeAppPayRequest request = new AlipayTradeAppPayRequest();
        AlipayTradeAppPayModel model = new AlipayTradeAppPayModel();
        String outTradeNo = UUID.randomUUID().toString().replace("-", "");
        // 订单号
        model.setOutTradeNo(outTradeNo);
        // 订单金额
        model.setTotalAmount("9.00");
        // 支付描述
        model.setSubject("大乐透");
        //
        request.setBizModel(model);
        request.setNotifyUrl("https://www.baidu.com/");
        request.setReturnUrl("https://www.baidu.com/");
        try {
            log.info("支付宝支付请求开始参数为:{}", JSON.toJSONString(request.getBizModel()));
            AlipayTradeAppPayResponse response = alipayClient.sdkExecute(request);
            log.info("支付宝支付请求结束，请求结果为:{}", JSON.toJSONString(response));
            if (response.isSuccess()) {
                log.info("支付宝支付请求成功，请求结果为:{}", response.getBody());
            } else {
                log.info("支付宝支付请求失败，失败原因为:{}", response.getSubMsg());
            }
            return R.ok(response.getBody());
        } catch (AlipayApiException e) {
            e.printStackTrace();
            return R.failed("系统异常");

        }
    }

    @Override
    public R orderDetailQuery(AlipayPaymentVo paymentVo) {
        AlipayClient alipayClient = this.initClient();
        AlipayTradeQueryRequest request = new AlipayTradeQueryRequest();
        AlipayTradeQueryModel model = new AlipayTradeQueryModel();
        // 订单号
        String outTradeNo = UUID.randomUUID().toString().replace("-", "");
        model.setOutTradeNo(outTradeNo);
        // 银联模式需要传入交易所属收单机构的pid
        model.setOrgPid("");
        request.setBizModel(model);
        try {
            log.info("支付宝支付请求开始参数为:{}", JSON.toJSONString(request.getBizModel()));
            AlipayTradeQueryResponse response = alipayClient.execute(request);
            log.info("支付宝支付请求结束，请求结果为:{}", JSON.toJSONString(response));
            if (response.isSuccess()) {
                log.info("支付宝支付请求成功，请求结果为:{}", response.getBody());
            } else {
                log.info("支付宝支付请求失败，失败原因为:{}", response.getSubMsg());
            }
            return R.ok(response.getBody());
        } catch (AlipayApiException e) {
            e.printStackTrace();
            return R.failed("系统异常");

        }


    }

    /**
     * 设置过期时间
     *
     * @return
     */
    public String getTimeOutDate(Integer timeCount) {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Calendar instance = Calendar.getInstance();
        instance.setTime(new Date());
        instance.add(Calendar.MINUTE, timeCount);
        Date time = instance.getTime();
        return dateFormat.format(time);
    }


    public static void main(String[] args) {
        AlipayClient alipayClient = new DefaultAlipayClient(AlipayConstants.URL,AlipayConstants.APPID,AlipayConstants.PRIVATE_KEY,AlipayConstants.FORMAT,AlipayConstants.CHARSET,AlipayConstants.ALIPAY_PUBLIC_KEY,"RSA2");
        AlipayTradeAppPayRequest request = new AlipayTradeAppPayRequest();
        request.setNotifyUrl("");
        JSONObject bizContent = new JSONObject();
        bizContent.put("out_trade_no", "20210817010101004");
        bizContent.put("total_amount", 0.01);
        bizContent.put("subject", "测试商品");
        bizContent.put("product_code", "QUICK_MSECURITY_PAY");
//bizContent.put("time_expire", "2022-08-01 22:00:00");

//// 商品明细信息，按需传入
//JSONArray goodsDetail = new JSONArray();
//JSONObject goods1 = new JSONObject();
//goods1.put("goods_id", "goodsNo1");
//goods1.put("goods_name", "子商品1");
//goods1.put("quantity", 1);
//goods1.put("price", 0.01);
//goodsDetail.add(goods1);
//bizContent.put("goods_detail", goodsDetail);

//// 扩展信息，按需传入
//JSONObject extendParams = new JSONObject();
//extendParams.put("sys_service_provider_id", "2088511833207846");
//bizContent.put("extend_params", extendParams);

        request.setBizContent(bizContent.toString());
        AlipayTradeAppPayResponse response = null;
        try {
            response = alipayClient.sdkExecute(request);
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        if(response.isSuccess()){
            System.out.println("调用成功");
        } else {
            System.out.println("调用失败");
        }
    }
}
